package com.example.zqq.shoushipassword.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Paint.Cap;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

import com.example.zqq.shoushipassword.MainActivity;
import com.example.zqq.shoushipassword.ModifyGuestActivity;
import com.example.zqq.shoushipassword.R;
import com.example.zqq.shoushipassword.ResatrtActivity;

import java.util.Timer;
import java.util.TimerTask;

//九宫格手势密码
//偏好存储：GUE_PWD，IS_SET_FIRST，FIRST_PWD，IS_SET，SECOND_ERROR，ERROR_POINT
public class NinePointLineView extends View {
//	private Token mToken;

    Context cxt;
    int flag;

    Paint linePaint = new Paint();
    Paint whiteLinePaint = new Paint();
    Paint textPaint = new Paint();

    Bitmap defaultBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.h5_b_normal);
    Bitmap selectedBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.h5_b_selected);

    int defaultBitmapRadius = defaultBitmap.getWidth() / 2;
    int selectedBitmapDiameter = selectedBitmap.getWidth();
    int selectedBitmapRadius = selectedBitmapDiameter / 2;

    PointInfo[] points = new PointInfo[9];
    PointInfo startPoint = null;

    int width, height;
    int moveX, moveY;
    boolean isUp = false;

    StringBuffer lockString = new StringBuffer();


    public NinePointLineView(Context context, int flagin) {
        super(context);
        cxt = context;
        flag = flagin;
//		mToken = new Token((Activity) cxt);
        // this.setBackgroundColor(Color.WHITE);//设置整个背景

        initPaint();
    }

    public NinePointLineView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // this.setBackgroundColor(Color.WHITE);//设置整个九宫格的背景
        initPaint();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        width = getWidth();
        height = getHeight();

        if (width != 0 && height != 0) {
            initPoints(points);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
    }

    private int startX = 0, startY = 0;

    @Override
    protected void onDraw(Canvas canvas) {
        // canvas.drawText("passwd:" + lockString, 0, 40, textPaint);
        if (moveX != 0 && moveY != 0 && startX != 0 && startY != 0) {
            // drawLine(canvas, startX, startY, moveX, moveY);
        }
        drawNinePoint(canvas);
        super.onDraw(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean flag = true;
        if (isUp) {
            finishDraw();
            flag = false;
        } else {
            handlingEvent(event);
            flag = true;
        }
        return flag;
    }

    private void handlingEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                moveX = (int) event.getX();
                moveY = (int) event.getY();

                for (PointInfo temp : points) {
                    if (temp == null) {
                        return;
                    }
                    if (temp.isInMyPlace(moveX, moveY) && temp.isSelected() == false) {
                        temp.setSelected(true);
                        startX = temp.getCenterX();
                        startY = temp.getCenterY();
                        int len = lockString.length();

                        if (len != 0) {
                            int preId = lockString.charAt(len - 1) - 48;
                            points[preId].setNextId(temp.getId());
                        }
                        lockString.append(temp.getId());
                        break;
                    }
                }
                invalidate(0, height - width, width, height);
                break;
            case MotionEvent.ACTION_DOWN:
                int downX = (int) event.getX();
                int downY = (int) event.getY();
                if (points.length > 0) {
                    for (PointInfo temp : points) {
                        if (temp == null) {
                            return;
                        }
                        if (temp.isInMyPlace(downX, downY)) {
                            temp.setSelected(true);
                            startPoint = temp;
                            startX = temp.getCenterX();
                            startY = temp.getCenterY();
                            lockString.append(temp.getId());
                            break;
                        }
                    }
                }
                invalidate(0, height - width, width, height);
                break;
            case MotionEvent.ACTION_UP:
                startX = startY = moveX = moveY = 0;
                isUp = true;
                invalidate();
                savePwd();
                break;
            default:
                break;
        }
    }

    private void finishDraw() {
        for (PointInfo temp : points) {
            if (temp == null) {
                return;
            }
            temp.setSelected(false);
            temp.setNextId(temp.getId());
        }
        lockString.delete(0, lockString.length());
        isUp = false;
        invalidate();
    }

    private void initPoints(PointInfo[] points) {
        int len = points.length;
        int seletedSpacing = (width - selectedBitmapDiameter * 3) / 4;
        int seletedX = seletedSpacing;
        int seletedY = height - width + seletedSpacing;
        int defaultX = seletedX + selectedBitmapRadius - defaultBitmapRadius;
        int defaultY = seletedY + selectedBitmapRadius - defaultBitmapRadius;
        Log.e("Tag-nineview-initpoint","selectedBitmapDiameter="+selectedBitmapDiameter);
        Log.e("Tag-nineview-initpoint","selectedBitmapRadius="+selectedBitmapRadius);
        Log.e("Tag-nineview-initpoint","width="+width);
        Log.e("Tag-nineview-initpoint","height="+height);
        Log.e("Tag-nineview-initpoint","defaultBitmapRadius="+defaultBitmapRadius);
        Log.e("Tag-nineview-initpoint","len="+len);
        Log.e("Tag-nineview-initpoint","seletedSpacing="+seletedSpacing);
        Log.e("Tag-nineview-initpoint","seletedX="+seletedX);
        Log.e("Tag-nineview-initpoint","seletedY="+seletedY);
        Log.e("Tag-nineview-initpoint","defaultX="+defaultX);
        Log.e("Tag-nineview-initpoint","defaultY="+defaultY);

        for (int i = 0; i < len; i++) {
            if (i == 3 || i == 6) {
                seletedX = seletedSpacing;
                seletedY += selectedBitmapDiameter + seletedSpacing;
                defaultX = seletedX + selectedBitmapRadius - defaultBitmapRadius;
                defaultY += selectedBitmapDiameter + seletedSpacing;
            }
            points[i] = new PointInfo(i, defaultX, defaultY, seletedX, seletedY);
            seletedX += selectedBitmapDiameter + seletedSpacing;
            defaultX += selectedBitmapDiameter + seletedSpacing;
        }
    }

    private void initPaint() {
        // initLinePaint(linePaint);
        initTextPaint(textPaint);
        initWhiteLinePaint(whiteLinePaint);
    }

    /**
     * @param paint
     */
    private void initTextPaint(Paint paint) {
        textPaint.setTextSize(30);
        textPaint.setAntiAlias(true);
        textPaint.setTypeface(Typeface.MONOSPACE);
    }


    /**
     * @param paint
     */
    private void initWhiteLinePaint(Paint paint) {
//		paint.setColor(Color.BLUE);
        paint.setColor(getResources().getColor(R.color.colorAccent));//guespwd
        paint.setStrokeWidth(20);// 设置两个点之间的线的宽度
        paint.setAntiAlias(true);
        paint.setStrokeCap(Cap.ROUND);
    }

    /**
     * @param canvas
     */
    private void drawNinePoint(Canvas canvas) {
        if (startPoint != null) {
            drawEachLine(canvas, startPoint);
        }
        for (PointInfo pointInfo : points) {
            if (pointInfo != null) {
                if (pointInfo.isSelected()) {
                    canvas.drawBitmap(selectedBitmap, pointInfo.getSeletedX(), pointInfo.getSeletedY(), null);
                }
                canvas.drawBitmap(defaultBitmap, pointInfo.getDefaultX(), pointInfo.getDefaultY(), null);
            }
        }
    }

    /**
     * @param canvas
     * @param point
     */
    private void drawEachLine(Canvas canvas, PointInfo point) {
        if (point.hasNextId()) {
            int n = point.getNextId();
            drawLine(canvas, point.getCenterX(), point.getCenterY(), points[n].getCenterX(), points[n].getCenterY());
            drawEachLine(canvas, points[n]);
        }
    }

    /**
     * @param canvas
     * @param startX
     * @param startY
     * @param stopX
     * @param stopY
     */
    private void drawLine(Canvas canvas, float startX, float startY, float stopX, float stopY) {
        canvas.drawLine(startX, startY, stopX, stopY, linePaint);
        canvas.drawLine(startX, startY, stopX, stopY, whiteLinePaint);
    }



    /**
     * @author zkwlx
     */
    private class PointInfo {
        private int id;
        private int nextId;
        private boolean selected;
        private int defaultX;
        private int defaultY;
        private int seletedX;
        private int seletedY;

        public PointInfo(int id, int defaultX, int defaultY, int seletedX, int seletedY) {
            this.id = id;
            this.nextId = id;
            this.defaultX = defaultX;
            this.defaultY = defaultY;
            this.seletedX = seletedX;
            this.seletedY = seletedY;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }

        public int getId() {
            return id;
        }

        public int getDefaultX() {
            return defaultX;
        }

        public int getDefaultY() {
            return defaultY;
        }

        public int getSeletedX() {
            return seletedX;
        }

        public int getSeletedY() {
            return seletedY;
        }

        public int getCenterX() {
            return seletedX + selectedBitmapRadius;
        }

        public int getCenterY() {
            return seletedY + selectedBitmapRadius;
        }

        public boolean hasNextId() {
            return nextId != id;
        }

        public int getNextId() {
            return nextId;
        }

        public void setNextId(int nextId) {
            this.nextId = nextId;
        }

        /**
         * @param x
         * @param y
         */
        public boolean isInMyPlace(int x, int y) {
            boolean inX = x > seletedX && x < (seletedX + selectedBitmapDiameter);
            boolean inY = y > seletedY && y < (seletedY + selectedBitmapDiameter);
            return (inX && inY);
        }
    }


    // 获取本次的密码
    public String getPwd() {
        return lockString.toString();
    }

    /**
     * 存储密码
     */
    public void savePwd() {
        //flag=-1时，设置手势密码
        //flag=0时，关闭手势密码
        //flag=1时，修改手势密码
        //flag=2时，从后台唤起程序时，若手势密码是开启的则提醒需要输入手势密码才能进入程序
        Intent intent = new Intent();
        SharedPreferences shareDate = cxt.getSharedPreferences("GUE_PWD", 0);
        if (flag == -1) {
            boolean isSetFirst = shareDate.getBoolean("IS_SET_FIRST", false);
            if (isSetFirst) {// 如果第一次已经设置密码，验证第二次和第一次是否一致
                String pwd = this.getPwd();
                String first_pwd = shareDate.getString("FIRST_PWD", "NO HAVE PWD");
                if (pwd.equals(first_pwd)) {// 第二次密码和第一次密码一样 设置成功
                    shareDate.edit().clear().apply();
                    shareDate.edit().putBoolean("IS_SET", true).apply();
                    shareDate.edit().putString("GUE_PWD", pwd).apply();
//                    mToken.saveToggle(true);
                    Timer time = new Timer();
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            ((Activity) cxt).finish();
                        }
                    };
//                    SmalltaurusApplication.isActivity = true;
//                    Toast.makeText(cxt, "密码设置成功", Toast.LENGTH_SHORT).show();
                    Toastmsg.Tmsg(cxt, "密码设置成功");
                    time.schedule(task, 1500);
                } else {// 第二次输入的密码和第一次输入的密码不一致
                    shareDate.edit().putBoolean("SECOND_ERROR", true).apply();
                    intent.setClass(cxt, MainActivity.class);
                    cxt.startActivity(intent);
                    ((Activity) cxt).finish();
                    ((Activity) cxt).overridePendingTransition(0, 0);
                }
            } else {// 第一次设置手势密码
                if (judgePoing(this.getPwd()) == 2) {
                    shareDate.edit().clear().apply();
                    shareDate.edit().putString("FIRST_PWD", this.getPwd()).apply();
                    shareDate.edit().putBoolean("IS_SET_FIRST", true).apply();
                    shareDate.edit().putString("GUE_PWD", this.getPwd()).apply();
                    intent.setClass(cxt, MainActivity.class);
                    cxt.startActivity(intent);
                    ((Activity) cxt).finish();
                    ((Activity) cxt).overridePendingTransition(0, 0);
                } else if (judgePoing(this.getPwd()) == 1) {
                    shareDate.edit().putBoolean("ERROR_POINT", true).apply();
                    intent.setClass(cxt, MainActivity.class);
                    cxt.startActivity(intent);
                    ((Activity) cxt).finish();
                    ((Activity) cxt).overridePendingTransition(0, 0);
                }
            }

            ///--------------------------------------------------------------------------------------
        } else if (flag == 0) {
            if (shareDate.getString("GUE_PWD", "NO HAVE PWD !").equals(this.getPwd())) {
//                mToken.saveToggle(false);
                //设置退出时间
                Timer time = new Timer();
                TimerTask task = new TimerTask() {
                    @Override
                    public void run() {
                        ((Activity) cxt).finish();
                    }
                };
                Toastmsg.Tmsg(cxt, "密码关闭成功");
                time.schedule(task, 1500);
                shareDate.edit().clear().apply();
            } else {
                //手势密码输入错误，重新输入
                shareDate.edit().putBoolean("SECOND_ERROR", true).apply();
                Intent i = new Intent(cxt, ModifyGuestActivity.class);
                i.putExtra("flag", 0);
                cxt.startActivity(i);
                ((Activity) cxt).finish();
                ((Activity) cxt).overridePendingTransition(0, 0);
            }

            ///--------------------------------------------------------------------------------------
        } else if (flag == 1) {
            if (shareDate.getString("GUE_PWD", "NO HAVE PWD !").equals(this.getPwd())) {
                //手势密码正确，跳转至设置手势密码页面
                shareDate.edit().clear().apply();
                cxt.startActivity(new Intent(cxt, MainActivity.class));
                ((Activity) cxt).finish();
                ((Activity) cxt).overridePendingTransition(0, 0);
            } else {
                //手势密码输入错误，重新输入
                shareDate.edit().putBoolean("SECOND_ERROR", true).apply();
                Intent i = new Intent(cxt, ModifyGuestActivity.class);
                i.putExtra("flag", 1);
                cxt.startActivity(i);
                ((Activity) cxt).finish();
                ((Activity) cxt).overridePendingTransition(0, 0);
            }

            ///--------------------------------------------------------------------------------------
        } else {
            if (shareDate.getString("GUE_PWD", "NO HAVE PWD !").equals(this.getPwd())) {
                //手势密码正确，进入程序
                shareDate.edit().putBoolean("SECOND_ERROR", false).apply();
                ((Activity) cxt).finish();
                ((Activity) cxt).overridePendingTransition(0, 0);

            } else {
                //手势密码输入错误，重新输入
                shareDate.edit().putBoolean("SECOND_ERROR", true).apply();
                Intent i = new Intent(cxt, ResatrtActivity.class);
                cxt.startActivity(i);
                ((Activity) cxt).finish();
                ((Activity) cxt).overridePendingTransition(0, 0);
            }
        }
    }


    //判断点的个数，至少需要四个点
    public int judgePoing(String str) {
        if (str.length() == 0 || str.equals(""))
            return 0;
        else if (str.length() < 4)
            return 1;
        else
            return 2;
    }

}
